package leetcode;

import java.util.List;

/**
 * Created by baoyunfeng on 2019/8/4.
 */
public class Add_Two_Numbers2 {

    public static void main(String args[]) {
        Add_Two_Numbers add_two_numbers = new Add_Two_Numbers();
        System.out.print(addTwoNumbers(add_two_numbers.parseIntToListNode(99), add_two_numbers
                .parseIntToListNode(1)));
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int num[] = new int[100];
        int maxLevel = 0;

        int level = 0;
        while (l1 != null) {
            num[level] = l1.val;
            maxLevel = level;
            level++;
            l1 = l1.next;
        }

        level = 0;
        while (l2 != null) {
            num[level] += l2.val;
            int carryLevel  = level;
            while (num[carryLevel] >= 10) {
                num[carryLevel] -= 10;
                carryLevel ++ ;
                num[carryLevel] += 1;
                if (carryLevel > maxLevel) {
                    maxLevel = carryLevel;
                }
            }
            if (level > maxLevel) {
                maxLevel = level;
            }
            level++;
            l2 = l2.next;
        }

        ListNode listNode = null;
        ListNode subNode = null;
        for(int i = 0 ;i <= maxLevel ;i++){
            if(listNode == null){
                listNode = new ListNode(num[i]);
                subNode = listNode;
            }else{
                ListNode node = new ListNode(num[i]);
                subNode.next = node;
                subNode = node;
            }
        }
        return listNode;
    }

}
